#!/usr/bin/env python
# coding=utf-8
import os
import sched
import smtplib
import sys
import time
from email.header import Header
from email.mime.text import MIMEText

import psutil

from Daemon import Daemon

MEM_WARN_LINE = 85
CPU_WARN_LINE = 90
SCHED_TIME = 60 * 30 * 1  # 单位，秒
IPADDRESS = '121.42.137.122'

def sendmail(content):
    subject = '[Python服务器监控]%s服务器监控预警' % IPADDRESS
    username = 'jerry6824'
    password = '1qaz2wsx'
    smtp_server = 'smtp.126.com'
    header = '您好！<br/> %s服务器性能预警<br/>' % IPADDRESS
    footer = '--------------------------------------------------------<br/>此为系统邮件请勿回复'
    content = '%s<br/>%s<br/>%s' % (header, content, footer)

    msg = MIMEText(content, 'html', 'utf-8')  # 中文需参数‘utf-8'，单字节字符不需要
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = "%s<jerry6824@126.com>" % Header('Python监控预警', 'utf-8')

    msg['to'] = 'liuyu2783@163.com'  # 单独收信人
    msg_to_list = ["liuy-af@glodon.com", "wangty@glodon.com"]  # 多个收信人

    smtp = smtplib.SMTP()
    smtp.connect(smtp_server)
    smtp.login(username, password)
    smtp.sendmail(msg['From'], msg_to_list, msg.as_string())
    smtp.quit()


def is_mem_warning():
    mem = psutil.virtual_memory()
    if mem.percent > MEM_WARN_LINE:
        return [True, mem]
    else:
        return [False, mem]


def is_cpu_warning():
    cpupercent = psutil.cpu_percent()
    if cpupercent > CPU_WARN_LINE:
        return [True, cpupercent]
    else:
        return [False, cpupercent]


def check_status():
    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    memwarn = is_mem_warning()
    is_send_mail = False
    mem = memwarn[1]

    if memwarn[0]:
        title = "内存预警[时间：%s]" % localtime
        memerr = str("%s\n 占用率：%s%%\n 总数：%s\n 已使用：%s\n 空闲：%s\n" % (title, mem.percent, mem.total, mem.used, mem.free))
        is_send_mail = True
    else:
        memerr = ''

    cpuwarn = is_cpu_warning()

    if cpuwarn[0]:
        title = "CPU预警[时间：%s]" % localtime
        cpuerr = str("%s\n 使用率 %s%%\n" % (title, cpuwarn[1]))
        is_send_mail = True
    else:
        cpuerr = ''

    if is_send_mail:
        sendmail("%s\n%s" % (memerr, cpuerr))
        sys.stderr.write("[error][%s] 监测异常\n %s\n%s \n" % (localtime, memerr, cpuerr))
        sys.stderr.flush()
    else:
        memmsg = str("内存情况 占用率：%s%% 总数：%s  已使用：%s  空闲：%s\n " % (mem.percent, mem.total, mem.used, mem.free))
        cpumsg = str("CPU使用率 %s%%\n" % cpuwarn[1])
        sys.stdout.write("[info][%s] 监测无异常\n %s %s" % (localtime, memmsg, cpumsg))
        sys.stdout.flush()

    schedule.enter(SCHED_TIME, 0, check_status, ())


class MyTestDaemon(Daemon):
    def run(self):
        localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sys.stdout.write('[info][%s] Daemon started with pid {%s}\n' % (localtime, os.getpid()))
        sys.stdout.flush()
        # 定时任务
        schedule.enter(SCHED_TIME, 0, check_status, ())
        schedule.run()


if __name__ == '__main__':
    schedule = sched.scheduler(time.time, time.sleep)
    PIDFILE = '/tmp/daemon-sysinfo.pid'
    LOG = '/tmp/daemon-sysinfo.log'
    daemon = MyTestDaemon(pidfile=PIDFILE, stdout=LOG, stderr=LOG)

    if len(sys.argv) != 2:
        print('Usage: {} [start|stop]'.format(sys.argv[0]))
        raise SystemExit(1)
    if 'start' == sys.argv[1]:
        daemon.start()
    elif 'stop' == sys.argv[1]:
        daemon.stop()
    elif 'restart' == sys.argv[1]:
        daemon.restart()
    else:
        print('Unknown command {!r}'.format(sys.argv[1]))
        raise SystemExit(1)
